package lc.q1_50;

import java.util.*;

public class Q47 {

    public List<List<Integer>> permuteUnique(int[] nums) {
        // 添加元素
        List<List<Integer>> results = new ArrayList<>();
        if (nums.length == 0) {
            return results;
        }
        // 排序
        Arrays.sort(nums);
        // 如何添加，先
        boolean[] used = new boolean[nums.length];
        Deque<Integer> deque = new ArrayDeque<>(nums.length);
        dfs(nums, nums.length, 0, used, deque, results);
        return results;
    }

    private void dfs(int[] nums, int len, int depth, boolean[] used, Deque<Integer> list,List<List<Integer>> results) {
        // 放元素
        if (depth == len) {
            results.add(new ArrayList<>(list));
            return;
        }
        // 回溯，先添加再撤回
        for (int i = 0; i < len; i++) {
            if (used[i]) {
                continue;
            }
            if (i > 0 && nums[i] == nums[i-1] && !used[i-1]) {
                continue;
            }
            list.addLast(nums[i]);
            used[i] = true;
            dfs(nums, len, depth + 1, used, list, results);
            used[i] = false;
            list.removeLast();
        }
    }

    public static void main(String[] args) {
        final Q47 q47 = new Q47();
        int[] nums = new int[]{1,1,2,2};
        final List<List<Integer>> lists = q47.permuteUnique(nums);
        System.out.println(lists);
    }

}
